package com.lute.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.security.oauth2.common.json.JSONException;
import org.springframework.security.oauth2.common.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lute.json.CalendarEntriesJSON;
import com.lute.model.Approver;
import com.lute.model.ClientAccountingPeriodState;
import com.lute.model.ClientAdmin;
import com.lute.model.Employee;
import com.lute.model.EmployeeAccountingPeriod;
import com.lute.model.EmployeeAccountingPeriodState;
import com.lute.model.EmployeeEntry;
import com.lute.model.User;
import com.lute.model.UserEntitlement;
import com.lute.utils.ServerErrorResponse;


@Controller
public class AccountingPeriodServlet {
	
	@RequestMapping(value="/getAccountingPeriod", method= RequestMethod.POST, headers="Content-type=application/json") 
	public @ResponseBody String currentAccountingPeriod(@RequestBody String accountingPeriodJSON,HttpServletRequest request) throws JSONException {
		String result = "";
		JSONObject jsonReq;
		JSONObject jsonRes = new JSONObject();
		
		HttpSession session = request.getSession(false);
		if(session == null) {
			jsonRes.put("result", ServerErrorResponse.USER_NOT_LOGGED_IN.toString());
			result = jsonRes.toString();
			return result;
		}
		
		try {
			jsonReq = new JSONObject(accountingPeriodJSON);
			jsonRes  = new JSONObject();
		} catch(JSONException e) {
			jsonRes.put("result", ServerErrorResponse.MALFORMED_REQUEST.toString());
			result = jsonRes.toString();
			return result;
		}
		
		/* check if json data was not malformed */
		if( (jsonReq.isNull("userId")) && (jsonReq.isNull("from")) ) {
			jsonRes.put("result",ServerErrorResponse.MALFORMED_REQUEST.toString());
			result = jsonRes.toString();
			return result;
		}
		
		String userId_str = jsonReq.getString("userId");
		int userId = Integer.parseInt(userId_str);
	    int sessionUserId = (Integer)session.getAttribute("sessionUserId");
	    String from = jsonReq.getString("from");
		String role = (String)session.getAttribute("role");
		jsonRes.put("result", "");
		
		EmployeeAccountingPeriod employeeAccountingPeriod = null;
		
		try {
			
			employeeAccountingPeriod = UserEntitlement.checkUserPrivilegeToEmployeeAccountingPeriod(from,sessionUserId,userId,role,jsonRes);
			
			if(!(jsonRes.get("result").equals(""))) {
				result = jsonRes.toString();
				System.out.println(result);
				return result;
			}
			
			if(employeeAccountingPeriod == null) {
				jsonRes.put("result", ServerErrorResponse.UNKNOWN_ACCOUNTING_PERIOD.toString());
				result = jsonRes.toString();
				return result;
			}
		
			SimpleDateFormat fromToDateFormater = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat rejectionDateFromater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			List<EmployeeEntry> employeeEntries = employeeAccountingPeriod.getEmployeeEntries();
			List<CalendarEntriesJSON> calendarEntries = new ArrayList<CalendarEntriesJSON>();
			
			CalendarEntriesJSON calendarEntriesJSON = null;
			for(EmployeeEntry empEntry: employeeEntries) {
				calendarEntriesJSON = new CalendarEntriesJSON();
				calendarEntriesJSON.setDate(fromToDateFormater.format(empEntry.getDate().getTime()));
				calendarEntriesJSON.setCompanyCategory(empEntry.getCompanyCategory().getName());
				calendarEntriesJSON.setCreativeHours(Integer.toString(empEntry.getCreativeHours()));
				calendarEntriesJSON.setHours(Integer.toString(empEntry.getHours()));
				calendarEntries.add(calendarEntriesJSON);
			}
		
			jsonRes.put("result", "OK");
			jsonRes.put("userId", userId_str);
			jsonRes.put("from", fromToDateFormater.format(employeeAccountingPeriod.getClientAccountingPeriod().getDate_from().getTime()));
			jsonRes.put("to", fromToDateFormater.format(employeeAccountingPeriod.getClientAccountingPeriod().getDate_to().getTime()));
			jsonRes.put("clientAccountingPeriodState", employeeAccountingPeriod.getClientAccountingPeriod().getClientAccountingPeriodState());
			jsonRes.put("employeeAccountingPeriodState", employeeAccountingPeriod.getEmployeeAccountingPeriodState());
			jsonRes.put("calendarEntries", calendarEntries);
			
			if(employeeAccountingPeriod.getEmployeeAccountingPeriodState().equals(EmployeeAccountingPeriodState.REJECTED_BY_APPROVER.toString()) || 
			   employeeAccountingPeriod.getEmployeeAccountingPeriodState().equals(EmployeeAccountingPeriodState.REJECTED_BY_CLIENT_ADMIN.toString())) {
				
				jsonRes.put("rejectionReason",employeeAccountingPeriod.getRejectionReason());
				jsonRes.put("rejectedBy", employeeAccountingPeriod.getRejectedBy());
				jsonRes.put("rejectionDate", rejectionDateFromater.format(employeeAccountingPeriod.getRejectionDate().getTime()));
			}
				
		
		}catch(NullPointerException npe) {
			jsonRes.put("result", ServerErrorResponse.INTERNAL_ERROR.toString());
			result = jsonRes.toString();
			System.out.println(result);
			return result;
		}
		
		result = jsonRes.toString();
		return result;
	}
}